package org.study.id.baidu.config;

import com.xfvape.uid.utils.DockerUtils;
import com.xfvape.uid.utils.NetUtils;
import com.xfvape.uid.worker.WorkerIdAssigner;
import com.xfvape.uid.worker.WorkerNodeType;
import jakarta.annotation.Resource;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.transaction.annotation.Transactional;
import org.study.id.baidu.mapper.WorkerNodeMapper;
import org.study.id.baidu.model.WorkerNode;

import java.time.LocalDate;

/**
 * 类的描述
 *
 * @author Administrator
 * @date 2021-05-27
 */
public class DisposableWorkerIdAssigner implements WorkerIdAssigner {
    @Resource
    private WorkerNodeMapper workerNodeMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public long assignWorkerId() {
        WorkerNode workerNode = new WorkerNode();
        workerNode.setLaunchDate(LocalDate.now());
        if (DockerUtils.isDocker()) {
            workerNode.setHostName(DockerUtils.getDockerHost());
            workerNode.setPort(DockerUtils.getDockerPort());
            workerNode.setType(WorkerNodeType.CONTAINER.value());
        } else {
            workerNode.setHostName(NetUtils.getLocalAddress());
            workerNode.setPort(System.currentTimeMillis() + "-" + RandomUtils.nextInt(100000));
            workerNode.setType(WorkerNodeType.ACTUAL.value());
        }
        workerNodeMapper.addWorkerNode(workerNode);
        return workerNode.getId();
    }
}
